/**
 * Created by Weizehua on 2017/1/25.
 */
import {Injectable} from "@angular/core";
import {RequestService} from "../../core/RequestService";
import {Hash} from "../../Utils/Hash";


@Injectable()
export class NewPostRequest {
    constructor(public service: RequestService) {
    }

    async upload(file: File): Promise<any> {
        let md5 = await this.calculateFileMd5(file);
        let {path, headers, signature} = await this.service.get('/upload/prepare',
            {
                md5: md5, size: file.size
            });
        await this.xhrUpload(file, path, headers);
        return await this.service.get('/upload/finished', {path:path, signature:signature});
    }

    calculateFileMd5(file) {
        return new Promise<string>((resolve, reject) => {
            let reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onerror = reject;
            reader.onabort = reject;
            reader.onload = async() => {
                resolve((await Hash.hash(reader.result, 'md5')).toString('base64'))
            };
        })
    }

    async xhrUpload(file: File, dstPath: string, headers: any) {
        return new Promise<any>((resolve, reject) => {
            // create request
            let xhr = new XMLHttpRequest();
            let remotePath = this.buildOSSRequestPath(dstPath);
            xhr.open('PUT', remotePath, true);
            for(let key in headers)
                xhr.setRequestHeader(key, headers[key]);
            xhr.send(file);
            xhr.onreadystatechange = () => {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        resolve(remotePath);
                    }
                    else {
                        reject(`Upload finished with error status: (${xhr.status}) ${xhr.statusText}`);
                    }
                }
            };
            xhr.onabort = ev => reject(ev);
            xhr.onerror = ev => reject(ev);
        })
    }

    private buildOSSRequestPath(dstPath: string) {
        return `${this.host}/${dstPath}`;
    }

    bucket = 'peres';
    region = 'oss-cn-shenzhen';
    host = `https://${this.bucket}.${this.region}.aliyuncs.com`;
}
